package com.xinxing.city.recovery.utils;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.hardware.Camera;
import android.text.Layout;
import android.text.StaticLayout;
import android.text.TextPaint;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;

import androidx.annotation.NonNull;

import com.google.gson.JsonObject;
import com.xinxing.city.recovery.Constant;
import com.xinxing.city.recovery.MainActivity;
import com.xinxing.city.recovery.MainActivity800;
import com.xinxing.city.recovery.RecoveryApplication;
import com.xinxing.city.recovery.net.OkHttpRequest;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.Objects;
import java.util.TimeZone;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

public class SimplePreviewBig extends SurfaceView implements SurfaceHolder.Callback {
    private static final String TAG = SimplePreview.class.getSimpleName();
    //保存该surface的持有者，只有holder才能修改相应的surface
    private SurfaceHolder surfaceHolder;
    public static int id;
    //保存相机的实例
    private Camera camera;
    private MainActivity mainActivity;

    public SimplePreviewBig(Context context) {
        super(context);

        //初始化holder与对应的回掉，这里的回掉就是自己
        surfaceHolder = getHolder();
        surfaceHolder.addCallback(this);
        mainActivity = (MainActivity) context;
    }

    //是一个比较安全的获取并打开相机的方法
    private static Camera getCameraInstance() {
        Camera tempCamera = null;
        try {
            Log.e("TTT", "id" + id);
            tempCamera = Camera.open(id);
        } catch (Exception e) {
            Log.d(TAG, "camera open failed" + e.getMessage());
        }
        return tempCamera;
    }

    //surface创建时会触发，通过camera将预览交给surface处理
    @Override
    public void surfaceCreated(@NonNull SurfaceHolder holder) {
        if (holder == null) {
            return;
        }
        this.surfaceHolder = holder;
        camera = getCameraInstance();
        Log.d(TAG, "surface create");
        try {
            //告知预览帧的数据交给谁
            if (camera != null) {
                camera.setPreviewDisplay(surfaceHolder);
//            camera.setDisplayOrientation(90);
                camera.startPreview();
            }
        } catch (IOException e) {
            Log.d(TAG, "Setting preview ERROR " + e.getMessage());
        }
    }

    @Override
    public void surfaceChanged(@NonNull SurfaceHolder surfaceHolder, int i, int i1, int i2) {
        this.surfaceHolder = surfaceHolder;
        Log.d(TAG, "surface changed");
        startPreview(false);
    }

    public void startPreview(boolean reuse) {
        if (camera != null && surfaceHolder != null) {
            try {
                if (!reuse) {
                    camera.setPreviewDisplay(surfaceHolder);
                }
                camera.startPreview();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public void surfaceDestroyed(@NonNull SurfaceHolder surfaceHolder) {
        surfaceHolder.removeCallback(this);
        if (camera != null) {
            camera.setPreviewCallback(null);
            camera.stopPreview();
            camera.release();
            camera = null;
        }
        Log.e("TTT", "xiaohui");
    }

    public void take(Context context, int num) {
        if (num == 1) {
            Constant.imageUrl.clear();
        }
        if (camera != null) {
            try {
                camera.takePicture(null, null, new Camera.PictureCallback() {
                    @Override
                    public void onPictureTaken(byte[] data, Camera camera) {
                        String path = context.getExternalFilesDir(null).getAbsolutePath() + "image" + num + ".jpg";
                        File file = new File(path);
//
                        Log.e("kong", "image path " + path);
                        try (OutputStream os = new FileOutputStream(file)) {
                            // 处理截图数据，保存到文件或进行其他操作
                            Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);


                            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, os);

                            File file2 = new File(path);
                            test(file2);
                            saveBitmapToFile(context, file2);
                            os.flush();

                        } catch (Exception e) {

                            e.printStackTrace();
                        }
                    }
                });
            } catch (RuntimeException e) {

            }
        }
    }

    // 保存Bitmap到文件
    public void saveBitmapToFile(Context context, File file) {

        Log.e("photo", "saveBitmapToFile   " + file.getPath());

        OkHttpRequest okHttpRequest = new OkHttpRequest(context, mainActivity.getSupportFragmentManager());

        okHttpRequest.sendFileRequestN("/sr-asset/v1/assets", file, RecoveryApplication.getInstance().getToken(), new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.e("photo", "桶内 onFailure");

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                JsonObject res = okHttpRequest.getResData();
                if (res == null) {
                    Log.e("photo", "桶内 null");
                    return;
                }

                Constant.imageUrl.add(res.get("data").getAsString());
                Log.e("photo", "桶内 " + res.get("data").getAsString() + "    " + Constant.imageUrl.size());

            }
        });

    }

    public void test(File file) throws IOException {
        Bitmap b = BitmapFactory.decodeFile(file.getPath());
        Bitmap newB = addTextWatermark(b, 20, Color.RED, 0, 0, true);


        File myCaptureFile = new File(file.getPath());
        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(myCaptureFile));
        newB.compress(Bitmap.CompressFormat.JPEG, 80, bos);
        bos.flush();
        bos.close();

    }

    /**
     * 给图片添加水印 当需要换行的时候，推荐使用StaticLayout 这种实现方式
     *
     * @param src      原bitmap
     * @param textSize 文字大小
     * @param x        距离图片位图的左边距
     * @param y        距离图片位图的上边距
     * @param recycle  是否回收bitmap，建议true
     */
    public Bitmap addTextWatermark(Bitmap src, int textSize, int color, float x, float y, boolean recycle) {
        Objects.requireNonNull(src, "src is null");
        Bitmap ret = src.copy(src.getConfig(), true);
        TextPaint paint = new TextPaint(Paint.ANTI_ALIAS_FLAG);
        Canvas canvas = new Canvas(ret);
        paint.setColor(color);
        paint.setTextSize(80);
        Rect bounds = new Rect();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());
        dateFormat.setTimeZone(TimeZone.getTimeZone("GMT+08:00"));
        String content =dateFormat.format(new Date());
        /*
        单行文字的实现代码
        paint.getTextBounds(content, 0, content.length(), bounds);
        canvas.drawText(content, x, y, paint);*/

        canvas.translate(x, y);
        StaticLayout myStaticLayout = new StaticLayout(content, paint, canvas.getWidth(), Layout.Alignment.ALIGN_NORMAL, 1.0f, 0.0f, false);
        myStaticLayout.draw(canvas);

//        canvas.drawBitmap(bitmap, 0, 0, null);//绘制小图片使用的代码
        if (recycle && !src.isRecycled()) src.recycle();
        return ret;
    }
}
